package com.pocketsweet.ui.fragments;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.avos.avoscloud.AVAnalytics;
import com.easemob.chat.EMContactManager;
import com.lidroid.xutils.ViewUtils;
import com.pocketsweet.C;
import com.pocketsweet.MLApplication;
import com.pocketsweet.R;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.AddFriend;
import com.pocketsweet.ui.Main;
import com.pocketsweet.ui.NewFollow;
import com.pocketsweet.ui.NewLover;
import com.pocketsweet.ui.Profile;
import com.pocketsweet.ui.uilib.ClearEditText;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.ui.uilib.HeaderLayout.onRightContainerListener;
import com.pocketsweet.ui.uilib.SideBar;
import com.pocketsweet.ui.uilib.SideBar.OnTouchingLetterChangedListener;
import com.pocketsweet.ui.uilib.TitlePopup;
import com.pocketsweet.ui.uilib.adapter.SortAdapter;
import com.pocketsweet.utils.CharacterParser;
import com.pocketsweet.utils.PinyinComparator;
import com.pocketsweet.utils.ShareReferanceUtils;
import com.pocketsweet.utils.SortModel;

public class FriendFragment extends Fragment implements View.OnClickListener {
	private View rootView;
	private static Context mContext;

	private List<JSONObject> contactList;
	private List<String> blackList;
	private ListView sortListView;
	private SideBar sideBar;
	private TextView dialog;
	private SortAdapter adapter;
	private static ClearEditText mClearEditText;
	private boolean hidden;

	private static TitlePopup titlePopup;
	private LinearLayout linNewLover;
	private LinearLayout linLikeMe;
	private LinearLayout linBankFriends;
	private ImageView ivNewFriend;
	private ImageView ivNewLike;

	/**
	 * 汉字转换成拼音的类
	 */
	private CharacterParser characterParser;
	private List<SortModel> SourceDateList;

	private List<MLUser> mFriendList;

	/**
	 * 根据拼音来排列ListView里面的数据类
	 */
	private PinyinComparator pinyinComparator;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_friend, null);
		ViewUtils.inject(this, rootView);
		return rootView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mContext = getActivity();
		initNaviagationComponent();
		initView();

	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		this.hidden = hidden;
		if (!hidden) {
			refresh();
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		if (!hidden) {
			refresh();
		}
	}

	private void initNaviagationComponent() {
	}

	public static void setHeaderFunction() {
		HeaderLayout header = Main.getInstance().getHeader();
		header.setRighttContainerClickListener(new onRightContainerListener() {

			@Override
			public void onClick() {
				// 跳到搜索添加好友
				Intent intent = new Intent(mContext, AddFriend.class);
				mContext.startActivity(intent);
			}
		});

		header.setLeftContainerClickListener(new onLeftContainerListener() {

			@Override
			public void onClick() {
				if (mClearEditText.getVisibility() == View.VISIBLE) {
					mClearEditText.setVisibility(View.GONE);
				} else {
					mClearEditText.setVisibility(View.VISIBLE);
				}
			}
		});
	}

	private void initView() {
		ivNewFriend = (ImageView) getView().findViewById(R.id.ivNewFriend);
		ivNewLike = (ImageView) getView().findViewById(R.id.ivNewLike);
		// 实例化汉字转拼音类
		characterParser = CharacterParser.getInstance();

		pinyinComparator = new PinyinComparator();

		sideBar = (SideBar) getView().findViewById(R.id.sidrbar);
		dialog = (TextView) getView().findViewById(R.id.dialog);
		linNewLover = (LinearLayout) getView().findViewById(R.id.linNewLover);
		linLikeMe = (LinearLayout) getView().findViewById(R.id.linLikeMe);
		linBankFriends = (LinearLayout) getView().findViewById(
				R.id.linBlankFriends);
		sideBar.setTextView(dialog);
		linNewLover.setOnClickListener(this);
		linLikeMe.setOnClickListener(this);

		// 设置右侧触摸监听
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {
				// 该字母首次出现的位置
				if (s.equals("↑")) {
					sortListView.setSelection(0);
				} else {
					int position = adapter.getPositionForSection(s.charAt(0));
					if (position != -1) {
						sortListView.setSelection(position);
					}
				}
			}
		});

		sortListView = (ListView) getView().findViewById(R.id.lvFriendList);
		sortListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// 这里要利用adapter.getItem(position)来获取当前position所对应的对象
				// User user = ((SortModel)
				// adapter.getItem(position)).getUser();
				// String userId = user.getUsername();

				// ToolKits.toast(MLApplication.getContext(),
				// ((SortModel) adapter.getItem(position)).getName());
			}
		});

		// 黑名单列表
		blackList = EMContactManager.getInstance().getBlackListUsernames();
		contactList = new ArrayList<JSONObject>();
		// 获取设置contactlist
		getContactList();
		SourceDateList = filledData(contactList);

		// 根据a-z进行排序源数据
		Collections.sort(SourceDateList, pinyinComparator);
		adapter = new SortAdapter(mContext, SourceDateList);
		sortListView.setAdapter(adapter);
		sortListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				JSONObject user = (JSONObject) adapter.getItem(position);
				// String username = user.getUsername();
				// String avatar = user.getAvatar();
				// String nickName = user.getNick();
				// startActivity(new Intent(getActivity(), ChatActivity.class)
				// .putExtra("userId", username)
				// .putExtra("avatar", avatar)
				// .putExtra("nickName", nickName));
				try {
					String selectedUserId = user.getString("objectId");
					Intent intent = new Intent(mContext, Profile.class);
					intent.putExtra("userId", selectedUserId);
					intent.putExtra("isLiked", true);
					mContext.startActivity(intent);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

		mClearEditText = (ClearEditText) getView().findViewById(
				R.id.filter_edit);

		// 根据输入框输入值的改变来过滤搜索
		mClearEditText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
				filterData(s.toString());
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
	}

	private void getContactList() {
//		contactList.clear();
//		// 获取本地好友列表
//		Map<String, User> users = MLApplication.getInstance().getContactList();
//		Iterator<Entry<String, User>> iterator = users.entrySet().iterator();
//		while (iterator.hasNext()) {
//			Entry<String, User> entry = iterator.next();
//			if (!entry.getKey().equals(Constant.NEW_FRIENDS_USERNAME)
//					&& !entry.getKey().equals(Constant.GROUP_USERNAME)
//					&& !entry.getKey().equals(Constant.NEW_CHAT_APPLY)
//					&& !entry.getKey().equals(Constant.SYSTEM)
//					&& !entry.getKey().equals(Constant.NEW_LIKER)
//					&& !entry.getKey().equals(UserService.getCurrentUserId())
//					&& !blackList.contains(entry.getKey())) {
//				// entry.getValue().setObjectId(users.getClass().get));
//				//contactList.add(entry.getValue());
//			}
//		}
//
//		if (contactList.size() <= 0) {
//			linBankFriends.setVisibility(View.VISIBLE);
//			sideBar.setVisibility(View.INVISIBLE);
//		} else {
//			linBankFriends.setVisibility(View.GONE);
//			sideBar.setVisibility(View.VISIBLE);
//		}
//		SourceDateList = filledData(contactList);
//		// 根据a-z进行排序源数据
//		Collections.sort(SourceDateList, pinyinComparator);
//		// Log.e("SourceDateList", SourceDateList.toString());
//		adapter = new SortAdapter(mContext, SourceDateList);
//		sortListView.setAdapter(adapter);
	}

	/**
	 * 为ListView填充数据
	 * 
	 * @param FriendList
	 * @return
	 */
	private List<SortModel> filledData(List<JSONObject> contactList) {
		List<SortModel> mSortList = new ArrayList<SortModel>();
		try {

			// Log.e("name", contactList.toString());
			for (int i = 0; i < contactList.size(); i++) {
				SortModel sortModel = new SortModel();
				sortModel.setName(contactList.get(i).getString("objectId"));

				// 汉字转换成拼音
				String pinyin = characterParser.getSelling(contactList.get(i)
						.getString("nickname"));
				if (pinyin.length() > 0) {
					String sortString = pinyin.substring(0, 1).toUpperCase();

					// 正则表达式，判断首字母是否是英文字母
					if (contactList.get(i).getInt("type") == C.USER_TYPE_RECOMMENDED) {
						sortModel.setSortLetters("☆");
					} else {
						if (sortString.matches("[A-Z]")) {
							sortModel.setSortLetters(sortString.toUpperCase());
						} else {
							sortModel.setSortLetters("#");
						}
					}

					sortModel.setUser(contactList.get(i));
					mSortList.add(sortModel);
				}
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return mSortList;

	}

	/**
	 * 根据输入框中的值来过滤数据并更新ListView
	 * 
	 * @param filterStr
	 */
	private void filterData(String filterStr) {
		List<SortModel> filterDateList = new ArrayList<SortModel>();

		if (TextUtils.isEmpty(filterStr)) {
			filterDateList = SourceDateList;
		} else {
			filterDateList.clear();
			for (SortModel sortModel : SourceDateList) {
				String name = sortModel.getName();
				if (name.indexOf(filterStr.toString()) != -1
						|| characterParser.getSelling(name).startsWith(
								filterStr.toString())) {
					filterDateList.add(sortModel);
				}
			}
		}

		// 根据a-z进行排序
		Collections.sort(filterDateList, pinyinComparator);
		adapter.updateListView(filterDateList);
	}

	public void refresh() {
		// 刷新新的恋人和喜欢的人的界面
		ShareReferanceUtils unreadInviteCount = new ShareReferanceUtils(
				MLApplication.getContext(), "UnreadInvite_"
						+ UserService.getCurrentUserId());
		int count = unreadInviteCount.getIntValue("count", 0);
		if (count == 0) {
			ivNewFriend.setVisibility(View.INVISIBLE);
		} else {
			ivNewFriend.setVisibility(View.VISIBLE);
		}
		// TODO 这里刷新喜欢的人的红点，跟上面一样
		ShareReferanceUtils unreadLikerCount = new ShareReferanceUtils(
				MLApplication.getContext(), "UnreadLiker_"
						+ UserService.getCurrentUserId());
		int count1 = unreadLikerCount.getIntValue("count", 0);
		if (count1 == 0) {
			ivNewLike.setVisibility(View.INVISIBLE);
		} else {
			ivNewLike.setVisibility(View.VISIBLE);
		}
		try {
			// 可能会在子线程中调到这方法
			getActivity().runOnUiThread(new Runnable() {
				public void run() {
					getContactList();
					adapter.notifyDataSetChanged();
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.linNewLover: // 新的恋人
			Intent intent = new Intent(getActivity(), NewLover.class);
			getActivity().startActivity(intent);
			break;
		case R.id.linLikeMe: // TODO 喜欢我的人
			Intent intent2 = new Intent(getActivity(), NewFollow.class);
			getActivity().startActivity(intent2);
			AVAnalytics.onEvent(getActivity(), "喜欢我的页面访问");
			break;
		}
	}
}
